package leetcode;

import pojo.TreeNode;

import java.util.*;

/**
 * 103. 二叉树的锯齿形层序遍历 https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/
 *
 * @author yujiafan
 * @version 1.0.0
 * @create 2022-12-29
 */
public class LeetCode103 {

    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        int flag = -1;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                list.add(poll.val);
                if (poll.left != null) {
                    queue.add(poll.left);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                }
            }
            // 反转
            if (flag == 1) {
                reverse(list);
            }
            flag = -flag;
            result.add(list);
        }
        return result;
    }

    public static void reverse(List<Integer> list) {
        int size = list.size();
        for (int i = 0; i < size / 2; i++) {
            int temp = list.get(i);
            list.set(i, list.get(size - i - 1));
            list.set(size - i - 1, temp);
        }
    }

    public static void main(String[] args) {
//        TreeNode treeNode = new TreeNode(3, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7)));
//        System.out.println(zigzagLevelOrder(treeNode));

        TreeNode treeNode1 = new TreeNode(0,new TreeNode(2,new TreeNode(1,new TreeNode(5),new TreeNode(1)),null),new TreeNode(4,new TreeNode(3,null,new TreeNode(6)),new TreeNode(-1,null,new TreeNode(8))));
        System.out.println(zigzagLevelOrder(treeNode1));
    }

}
